package com.thilux.lame.file;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;

public class LameFileUtility {

	public static String getFileContentAsString(File file) {

		try {

			BufferedReader reader = new BufferedReader(new FileReader(file));
			String line = null;
			StringBuilder stringBuilder = new StringBuilder();
			String ls = System.getProperty("line.separator");

			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line);
				stringBuilder.append(ls);
			}

			reader.close();
			
			return stringBuilder.toString();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;

	}

	public static File getLastFileFromDirectory(File directory)
			throws Exception {

		if (directory.isDirectory()) {

			List<File> files = Arrays.asList(directory.listFiles());

			if (files.size() == 0) {

				throw new Exception("Directory [" + directory.getAbsolutePath()
						+ "] is empty!!!!");
			} else {

				long lastModified = Long.MIN_VALUE;

				File choice = null;

				for (File currFile : files) {

					if (currFile.lastModified() > lastModified) {

						choice = currFile;
						lastModified = currFile.lastModified();

					}
				}

				return choice;

			}

		} else {

			throw new Exception("File " + directory.getAbsolutePath()
					+ "is not a directory");
		}

	}

}
